//
//  PurchasingViewController.m
//  FreightAssistant
//
//  Created by Mac mini on 15/12/8.
//  Copyright © 2015年 leo. All rights reserved.
//

#import "PurchaseOrderEditViewController.h"

#import "KKTableHeaderView.h"
#import "KKTableFooterView.h"

#import "KKEditTableViewCell.h"

#import "LogisticsListViewController.h"
#import "CustomerListTableViewController.h"
#import "CommodityListTableViewController.h"

#import "KKPurchaseCommodityItemList.h"
#import "KKLogisticsItemList.h"

@interface PurchaseOrderEditViewController () {
    
    NSMutableArray *_selectedCommodityList;
    
    NSString *_customerIdentifier;         /**< 买家标识*/
    NSString *_customerNameValue;          /**< 买家姓名*/
    NSString *_customerPhoneValue;         /**< 买家手机号*/
    NSString *_customerAddressValue;       /**< 买家地址*/
    
    NSString *_transporterIdentifier;   /**< 物流商标识*/
    NSString *_transporterNameValue;    /**< 物流名称*/
    NSString *_transporterNumberValue;  /**< 快递单号*/
    NSString *_transporterAmountValue;  /**< 运费*/
    
    NSString *_orderDateValue;          /**< 订单生成时间*/
    
    KKTableFooterView *_tableFooterView;
    KKTableFooterView *_commodityTableFooterView;
}

@end

@implementation PurchaseOrderEditViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title = @"新增采购单";
    
    [self.tableView registerNib: [UINib nibWithNibName: NSStringFromClass([KKEditTableViewCell class]) bundle:[NSBundle mainBundle]] forCellReuseIdentifier: KKEditTableViewCellIdentifier];
    
    {
        _tableFooterView = [KKTableFooterView footerViewOfSubmitButtonWithTableView: self.tableView];
        __weak typeof(_tableFooterView) weakTableFooterView = _tableFooterView;
        self.keyboardStateBlock = ^(BOOL show){
            
            weakTableFooterView.kk_submitButton.enabled = !show;
        };
        [_tableFooterView.kk_submitButton addTarget: self action: @selector(actionOfSave:) forControlEvents: UIControlEventTouchUpInside];
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear: animated];
    
    [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(updateFooterViewData) name: NSNotificationNameIsPurchaseCommodityListAmountName object: nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear: animated];
    
    [[NSNotificationCenter defaultCenter] removeObserver: self];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Private methods

- (void)updateFooterViewData {
    
    double totalPrice = 0.0;
    for (KKPurchaseCommodityItem *commodityItem in _selectedCommodityList) {
        
        totalPrice += [commodityItem totalAmount];
    }
    
    _commodityTableFooterView.kk_titleLabel.text = [NSString stringWithFormat: @"总金额:%.2f",totalPrice];
}

- (void)updateSelectedCommodityItemsWithResponseArray:(NSArray*)responseArray {
    
    if ([responseArray isKindOfClass: [NSArray class]]) {
        
        _selectedCommodityList = [NSMutableArray array];
        
        for (KKCommodityItem *item in responseArray) {
            
            KKPurchaseCommodityItem *selectedItem = [[KKPurchaseCommodityItem alloc] initWithItem: item];
            [_selectedCommodityList addObject: selectedItem];
        }
        [self.tableView reloadSections: [NSIndexSet indexSetWithIndex: 1] withRowAnimation: UITableViewRowAnimationAutomatic];
    }
}

#pragma mark - Action methods

- (void)saveOrderToDataBase {
    
    
    NSString* createTime = [NSString stringWithFormat: @"%f",[NSDate timeIntervalSinceReferenceDate]];
    
    NSMutableDictionary *records = [NSMutableDictionary dictionary];
    [records setValue: createTime forKey: @"createTime"];
    [records setValue: @0 forKey: @"state"];
    
    NSMutableDictionary *logisticsRecords = [NSMutableDictionary dictionary];
    [logisticsRecords setValue: _transporterIdentifier forKey: @"logisticsId"];
    [logisticsRecords setValue: _transporterNumberValue forKey: @"number"];
    [logisticsRecords setValue: _transporterAmountValue forKey: @"amount"];
    
    NSMutableArray *commodityItems = [NSMutableArray array];
    
    for (KKPurchaseCommodityItem *commodityItem in _selectedCommodityList) {
        
        NSMutableDictionary *commodityDictionary = [NSMutableDictionary dictionary];
        
        [commodityDictionary setValue: commodityItem.kk_commodityItem.kk_identifier forKey: @"commodityId"];
        [commodityDictionary setValue: commodityItem.kk_name forKey: @"name"];
        [commodityDictionary setValue: commodityItem.kk_currency forKey: @"currency"];
        [commodityDictionary setValue: commodityItem.kk_price forKey: @"price"];
        [commodityDictionary setValue: commodityItem.kk_number forKey: @"number"];
        [commodityDictionary setValue: commodityItem.kk_amount forKey: @"amount"];
        
        [commodityItems addObject: commodityDictionary];
    }

    __weak typeof(self) weakSelf = self;
    
    [KKDataBaseAPIInterface addPurchaseOrderWithOrderRecords: records customerIdentifier: _customerIdentifier commodityItems: commodityItems logisticsRecords: logisticsRecords successful:^(id object) {
        [weakSelf saveSuccessful];
    } faile:^(NSString *error) {
        [[KKResultAlertView sharedInstance] alertViewShowMessage: error andWithSuccessful: true andWithCallBack: nil];
    }];
    
}

- (void)saveSuccessful {
    
    __weak typeof(self) weakSelf = self;
    [[KKResultAlertView sharedInstance] alertViewShowMessage: @"创建成功" andWithSuccessful: true andWithCallBack:^{
        
        [weakSelf.navigationController popViewControllerAnimated: true];
    }];
}

#pragma mark - UITableView method

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    NSInteger rows = 0;
    
    switch (section) {
        case 0:
        {
            rows = 2;
        }
            break;
        case 1:
        {
            rows = _selectedCommodityList.count;
        }
            break;
        case 2:
        {
            rows = 3;
        }
            break;
            
        default:
            break;
    }
    return rows;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger height = 44;
    
    if (indexPath.section == 1) {
        height = 120;
    }
    
    return height;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSInteger section = indexPath.section;
    
    NSInteger row = indexPath.row;
    
    if (section == 0) {
        
        KKEditTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: KKEditTableViewCellIdentifier forIndexPath: indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.accessoryType = UITableViewCellAccessoryNone;
        switch (row) {
            case 0:
            {
                cell.kk_titleLabel.text = @"卖家姓名:";
                cell.kk_valueTextField.placeholder = @"请输入卖家姓名";
                cell.kk_valueTextField.text = _customerNameValue;
                cell.editHandle = ^(NSString *value, NSString *key) {
                    _customerNameValue = value;
                };
            }
                break;
            case 1:
            {
                cell.kk_titleLabel.text = @"手机号:";
                cell.kk_valueTextField.placeholder = @"请输入卖家手机号";
                cell.kk_valueTextField.text = _customerPhoneValue;
                cell.editHandle = ^(NSString *value, NSString *key) {
                    _customerPhoneValue = value;
                };
            }
                break;
            case 2:
            {
                cell.kk_titleLabel.text = @"买家地址:";
                cell.kk_valueTextField.placeholder = @"请输入买家地址";
                cell.kk_valueTextField.text = _customerAddressValue;
                cell.editHandle = ^(NSString *value, NSString *key) {
                    _customerAddressValue = value;
                };
            }
                break;
                
            default:
                break;
        }
        
        return cell;
    }
    else if (section == 1) {
        
        PurchaseCommodityTableViewCell *cell = [PurchaseCommodityTableViewCell cellFromTableView: tableView];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        KKPurchaseCommodityItem *commodityItem = [_selectedCommodityList objectAtIndex: row];
        [cell setKk_item: commodityItem];
        
        return cell;
    }
    else if (section == 2) {
        
        KKEditTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: KKEditTableViewCellIdentifier forIndexPath: indexPath];
        
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        cell.textLabel.textColor = [UIColor darkGrayColor];
        cell.textLabel.font = [UIFont systemFontOfSize: 15];
        
        switch (row) {
            case 0:
            {
                cell.kk_titleLabel.text = @"快递商:";
                cell.kk_valueTextField.placeholder = @"请选择快递商";
                cell.kk_valueTextField.enabled = false;
                cell.kk_valueTextField.text = _transporterNameValue;
            }
                break;
            case 1:
            {
                cell.kk_titleLabel.text = @"快递单号:";
                cell.kk_valueTextField.placeholder = @"请输入快递单号";
                cell.kk_valueTextField.text = _transporterNumberValue;
                
                cell.editHandle = ^(NSString *value, NSString *key) {
                    
                    _transporterNumberValue = value;
                };
            }
                break;
            case 2:
            {
                cell.kk_titleLabel.text = @"快递费用:";
                cell.kk_valueTextField.placeholder = @"请输入运费(默认为免邮费)";
                cell.kk_valueTextField.text = _transporterAmountValue;
                
                cell.editHandle = ^(NSString *value, NSString *key) {
                    
                    _transporterAmountValue = value;
                };
                cell.accessoryType = UITableViewCellAccessoryNone;
            }
                break;
                
            default:
                break;
        }
        
        return cell;
    }
    
    return nil;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return indexPath.section == 1 ? true : false;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSInteger section = indexPath.section;
    if (section == 1) {
        
//        KKOrderCommodityItem *commodityItem = [_selectedCommodityList objectAtIndex: indexPath.row];
//        [_selectedCommodityList removeObject: commodityItem];
        
        [self.tableView reloadSections: [NSIndexSet indexSetWithIndex: 1] withRowAnimation: UITableViewRowAnimationAutomatic];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 40;
}

- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView *headerView = [[UIView alloc] initWithFrame: CGRectMake(0, 0, CGRectGetWidth(tableView.bounds), 40)];
    
    headerView.backgroundColor = [UIColor colorWithHexString: @"#2eb1e7"];
    
    UILabel *headerTitleLabel = [[UILabel alloc] initWithFrame: CGRectMake(10, 0, 120, CGRectGetHeight(headerView.bounds))];
    headerTitleLabel.backgroundColor = [UIColor clearColor];
    headerTitleLabel.textColor = [UIColor whiteColor];
    [headerView addSubview: headerTitleLabel];
    
    UIButton *addButton = [UIButton buttonWithType: UIButtonTypeCustom];
    addButton.frame = CGRectMake(CGRectGetWidth(tableView.bounds) - 40, 5, 30, 30);
    //    [addButton setBackgroundImage: [UIImage imageNamed: @"button_add_item"] forState: UIControlStateNormal];
    addButton.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
    [headerView addSubview: addButton];
    
    switch (section) {
        case 0:
            headerTitleLabel.text = @"供应商信息";
            //            button_commodity_add
            [addButton setBackgroundImage: [UIImage imageNamed: @"button_customer_add"] forState: UIControlStateNormal];
            [addButton addTarget: self action: @selector(actionOfChooseCustomer:) forControlEvents: UIControlEventTouchUpInside];
            break;
        case 1:
        {
            headerTitleLabel.text = @"货品信息";
            [addButton setBackgroundImage: [UIImage imageNamed: @"button_commodity_add"] forState: UIControlStateNormal];
            [addButton addTarget: self action: @selector(actionOfChooseCommodityItems:) forControlEvents: UIControlEventTouchUpInside];
        }
            break;
        case 2:
            headerTitleLabel.text = @"快递信息";
            [addButton removeFromSuperview];
            break;
            
        default:
            break;
    }
    
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    if (section == 1) {
        return 22;
    }
    
    return CGFLOAT_MIN;
}

- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    if (section == 1) {
        
        if (_commodityTableFooterView == nil) {
            _commodityTableFooterView = [KKTableFooterView footerViewOfTitleLabelWithTableView: tableView];
        }
        
        [self updateFooterViewData];
        
        return _commodityTableFooterView;
    }
    
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    if (section == 2) {
        
        __weak UITableView *weakTableView = self.tableView;
        if (row == 0) {
            LogisticsListViewController *logisticsListViewController = [LogisticsListViewController viewControllerFromStoryboard];
            logisticsListViewController.viewcontrollerType = KKViewControllerTypeChoose;
            logisticsListViewController.editResultBlock = ^(id object) {
                
                if ([object isKindOfClass: [KKLogisticsItem class]]) {
                    KKLogisticsItem *item = (KKLogisticsItem*)object;
                    
                    _transporterIdentifier = item.kk_identifier;
                    _transporterNameValue = item.kk_name;
                    [weakTableView reloadSections: [NSIndexSet indexSetWithIndex: 2] withRowAnimation: UITableViewRowAnimationAutomatic];
                }
            };
            [self.navigationController pushViewController: logisticsListViewController animated: true];
        }
        else if (row == 1) {
            
            //            KKScanningViewController *scanningViewController = [KKScanningViewController new];
            //            scanningViewController.resultHandle = ^(NSString *reslut){
            //                _transporterNumberValue = reslut;
            //                [weakTableView reloadSections: [NSIndexSet indexSetWithIndex: 2] withRowAnimation: UITableViewRowAnimationAutomatic];
            //            };
            //            [self.navigationController pushViewController: scanningViewController animated: true];
        }
    }
}

#pragma mark - Action methods

- (void)actionOfChooseCustomer:(UIButton*)item {
    
    CustomerListTableViewController *customerListTableViewController = [CustomerListTableViewController viewControllerFromStoryboard];
    
    customerListTableViewController.viewcontrollerType = KKViewControllerTypeChoose;
    
    __weak UITableView *weakTableView = self.tableView;
    
    customerListTableViewController.editResultBlock = ^(id object) {
        
        if ([object isKindOfClass: [KKCustomerItem class]]) {
            KKCustomerItem *item = (KKCustomerItem*)object;
            
            _customerIdentifier = item.kk_identifier;
            _customerNameValue = item.kk_name;
            _customerAddressValue = item.kk_address;
            _customerPhoneValue = item.kk_phone;
            
            [weakTableView reloadSections: [NSIndexSet indexSetWithIndex: 0] withRowAnimation: UITableViewRowAnimationAutomatic];
        }
    };
    [self.navigationController pushViewController: customerListTableViewController animated: true];
}

- (void)actionOfChooseCommodityItems:(UIButton*)item {
    
    CommodityListTableViewController *commodityListTableViewController = [CommodityListTableViewController viewControllerFromStoryboard];
    commodityListTableViewController.type = CommodityListViewControllerTypeIsPurchaseOrder;
    
    __weak typeof(self) weakSelf = self;
    commodityListTableViewController.editResultBlock = ^(id object) {
        [weakSelf updateSelectedCommodityItemsWithResponseArray: object];
    };
    
    [self.navigationController pushViewController: commodityListTableViewController animated: true];
}

- (void)actionOfSave:(UIButton*)item {
    
    if (_customerNameValue.length == 0 || _customerPhoneValue.length == 0 || _customerAddressValue.length == 0) {
        
        [[KKResultAlertView sharedInstance] alertViewShowMessage: @"卖家信息有误" andWithSuccessful: false andWithCallBack: nil];
        return;
    }
    if (_selectedCommodityList.count == 0) {
        [[KKResultAlertView sharedInstance] alertViewShowMessage: @"货品信息为空" andWithSuccessful: false andWithCallBack: nil];
        return;
    }
    if (_transporterNameValue.length == 0 || _transporterNumberValue.length == 0) {
        
        [[KKResultAlertView sharedInstance] alertViewShowMessage: @"快递信息有误" andWithSuccessful: false andWithCallBack: nil];
        return;
    }
    if (_customerIdentifier.length == 0) {
        
        [[KKAlertView shareInterce] showWithTitle: nil andWithMessage: @"请先添加客户信息，再次新增订单" andWithCancelTitle: nil andWithCancelHandle: nil andWithSureTitle: @"确认" andWithSureHandle: nil];
        return;
    }
    
    [self saveOrderToDataBase];
}
@end
